﻿using GPS.MODELS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPS.DataAccessLayer;
using AutoMapper;
using PagedList;
using GPS.ENTITYS;
using GPS.COMMON;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using Microsoft.AspNet.Identity;
using NPOI.HSSF.UserModel;
using OfficeOpenXml;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace GPS.Controllers.GPS_CapPhep
{
    public class GPS_GiayPhepDSPhuongTienController : Controller
    {
        DbContextHelper<GPS_NVContext> _db = Singleton<DbContextHelper<GPS_NVContext>>.Inst;
        public GPS.MODELS.ApplicationUser getCurrentUser()
        {
            ApplicationDbContext dbUser = new ApplicationDbContext();
            string userId = User.Identity.GetUserId();
            ApplicationUser _currentUser = dbUser.Users.Find(userId);
            return _currentUser;
        }

        #region Index
        public ActionResult Index(ViewModelDSDPT SearchModel, int? currentPage)
        {
            //checkuser
            string DVGTVT_MA = this.getCurrentUser().MA_TINHTP;
            ViewBag.checkuser = DVGTVT_MA;
            string getdvgtvt_Ma = GPS.DAL.Check_User.CheckUser(this.getCurrentUser().MA_TINHTP, SearchModel.pDVGTVT_MA);
            SearchModel.pDVGTVT_MA = getdvgtvt_Ma;
            TempData["DVGTVT_MA"] = getdvgtvt_Ma;
            initialCategorySearchAction(SearchModel);

            DataSet ds = RunPKG(SearchModel);

            var model = new List<CrudModelDSDPT_Export>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                model = COMMON.Helpers.MapDataTableToList<CrudModelDSDPT_Export>(ds.Tables[0]);
                ViewBag.TotalRow = model.Count();
                Int16 icout = 1;
                foreach (var item in model)
                {
                    item.STT = icout.ToString();
                    icout++;
                }

                var _model = new CrudModelDSDPT_Export();
                if (SearchModel.btnExportWord =="ExportWord")
                {
                    //getdvgtvt_Ma
                    _model.DVGTVT_TEN = _db.Filter<SDONVIGTVT>(x => x.DVGTVT_MA == getdvgtvt_Ma && x.DVGTVT_MAQL == "40").Select(x => x.DVGTVT_TEN).FirstOrDefault();
                    _model.DVGTVT_MASO = _db.Filter<SDONVIGTVT>(x => x.DVGTVT_MAQL == "40").Select(x => x.DVGTVT_TEN).FirstOrDefault();

                    _model.LIST = COMMON.Helpers.MapDataTableToList<CrudModelDSDPT_Export>(ds.Tables[0]);
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        _model.LIST[i].CB_PT_BIENSO = ds.Tables[0].Rows[i]["CB_PT_BIENSO"].ToString();
                        _model.LIST[i].XE_CSDT = ds.Tables[0].Rows[i]["XE_CSDT"].ToString();
                        _model.LIST[i].XE_HOPDONG = ds.Tables[0].Rows[i]["XE_HOPDONG"].ToString();
                        _model.LIST[i].PT_NHANHIEU = ds.Tables[0].Rows[i]["PT_NHANHIEU"].ToString();
                        _model.LIST[i].PT_LOAIXE = ds.Tables[0].Rows[i]["PT_LOAIXE"].ToString();
                        _model.LIST[i].PT_SOMAY = ds.Tables[0].Rows[i]["PT_SOMAY"].ToString();
                        _model.LIST[i].CB_PT_NGAYGCNKD = ds.Tables[0].Rows[i]["CB_PT_NGAYGCNKD"].ToString();
                        _model.LIST[i].CB_PT_NGAYHHGCNKD = ds.Tables[0].Rows[i]["CB_PT_NGAYHHGCNKD"].ToString();
                    }
                    _model.STT = "Số TT";
                    _model.CB_PT_BIENSO = "Biển số đăng ký";
                    _model.XE_CSDT = "Xe cơ sở đào tạo";
                    _model.XE_HOPDONG = "Xe hợp đồng";
                    _model.PT_NHANHIEU = "Nhãn hiệu";
                    _model.PT_LOAIXE = "Loại xe";
                    _model.PT_SOMAY = "Số máy";
                    _model.CB_PT_NGAYGCNKD = "Ngày cấp cấp GCNKD";
                    _model.CB_PT_NGAYGCNKD = "Ngày cấp cấp GCNKD";
                    _model.LIST = COMMON.Helpers.MapDataTableToList<CrudModelDSDPT_Export>(ds.Tables[0]);
                    _model.LIST.Insert(0, _model);
                    byte[] contentFile = null;
                    contentFile = GPS.ENTITYS.EXPORTWORD_DSDPT_Export.EXPORT_DSDPT_Export(Server.MapPath("~/Templates/GPS_Word/DanhSachDeNghiXeTapLai.docx"), _model, "DocxGenericReport");
                    string nameOutput = "BienBanHopPhanCongChamThi" + DateTime.Now.ToShortDateString() + ".docx";
                    return File(contentFile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", nameOutput);
                }
            }

            var pageIndex = SearchModel.Page ?? 1;
            SearchModel.SearchResults = model.ToPagedList(pageIndex, GPS.COMMON.Constants.PageSize);
            return View(SearchModel);
        }
        #endregion

        public void initialCategorySearchAction(ViewModelDSDPT viewModel)
        {
            ViewBag.KH_MAs = new SelectList(_db.Filter<DPT>(o => o.PT_BIENSO == viewModel.pPT_BIENSO), "PT_BIENSO", "PT_BIENSO");
        }
        public DataSet RunPKG(ViewModelDSDPT item)
        {
            try
            {
                DataSet ds = OracleHelper.ExecuteDataset(_db.DbContext.Database.Connection.ConnectionString, CommandType.StoredProcedure, "GPS_CAPPHEP.GPS_CAPPHEP_DSXTL"
                                                         , new OracleParameter("pDVGTVT_MA", OracleDbType.Varchar2, string.IsNullOrWhiteSpace(item.pDVGTVT_MA) ? DBNull.Value : (object)item.pDVGTVT_MA, ParameterDirection.Input)
                                                         , new OracleParameter("pRET", OracleDbType.RefCursor, ParameterDirection.Output)
                                                        );

                return ds;
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        #region Detail
        public ActionResult Detail(string id1, string id2)
        {
            CrudModelDPT _model = new CrudModelDPT();
            DPT model = _db.GetOne<DPT>(o => o.PT_BIENSO == id1 && o.PT_DVGTVT_MA == id2);
            GPS.COMMON.Helpers.CopyObject<CrudModelDPT>(model, ref _model);

            initialCategoryDetailAction(_model);
            return PartialView("_Detail", _model);
        }

        public void initialCategoryDetailAction(CrudModelDPT view)
        {
            if (view.PT_ACTIVE == "1")
            {
                ViewBag.txtTrangThai = "Hiệu Lực";
            }
            else
            {
                ViewBag.txtTrangThai = "Không Hiệu Lực";
            }
            ViewBag.PT_DVGTVT_MAss = _db.Filter<SDONVIGTVT>(o => o.DVGTVT_MAQL == "40"
                                    && o.DVGTVT_MA == view.PT_DVGTVT_MA).Select(x => x.DVGTVT_TEN).FirstOrDefault();
        }
        #endregion

        #region"Biến động Phương tiện"

        #endregion

        #region xuất giấy

        [HttpGet]
        public ActionResult Export(decimal id1, string id2)
        {
            string _PT_DVGTVT_MA = id2;
            DPT model = _db.GetOne<DPT>(x => x.ID == id1 && x.PT_DVGTVT_MA == _PT_DVGTVT_MA);

            ViewBag.DVGTVT_MAs = new SelectList(_db.Filter<SDONVIGTVT>(o => o.DVGTVT_MAQL == "40"), "DVGTVT_MA", "DVGTVT_TEN");
            CrudModelDPT_Export _model = new CrudModelDPT_Export();
            _model.CB_PT_DVGTVT_MA = model.PT_DVGTVT_MA;
            _model.DVGTVT_TEN = _db.GetOne<SDONVIGTVT>(x => x.DVGTVT_MA == model.PT_DVGTVT_MA).DVGTVT_TEN;
            _model.CB_PT_BIENSO = model.PT_BIENSO;
            _model.PT_COSOHUU = model.PT_COSOHUU == 0 ? "Chính chủ" : "Hợp đồng";
            //_model.DCP_GV_DVGTVT_TEN = model.GV_TEN;
            _model.PT_NHANHIEU = model.PT_NHANHIEU;
            _model.PT_MAUXE = model.PT_MAUXE;
            ViewBag.CB_PT_SOGPXTL = model.PT_SOGPXTL;
            ViewBag.CB_PT_NGAYGPXTL = model.PT_NGAYGPXTL;
            ViewBag.CB_PT_NGAYHHGPXTL = model.PT_NGAYHHGPXTL;
            return View("Export", _model);
        }

        [HttpPost]
        public ActionResult Export(CrudModelDPT_Export model, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                //DCPGV _model = new DCPGV();
                //string hodem = _db.GetOne<DGV>(x => x.GV_MA == model.DCP_GV_MA).GV_HODEM;
                //string Ten = _db.GetOne<DGV>(x => x.GV_MA == model.DCP_GV_MA).GV_TEN;
                //GPS.COMMON.Helpers.CopyObject<DCPGV>(model, ref _model);
                //_model.DCP_GV_NGAYNHAP = DateTime.Now;
                //_model.DCP_GV_NGUOINHAP = "admin";
                //_model.DCP_GV_HODEM = hodem;
                //_model.DCP_GV_DVGTVT_TEN = Ten;
                //_model.ID = EFSequence.GetNextValue("SEQ_DLSGV_ID");

                //_db.Insert<DCPGV>(_model);

                ////update trạng thái DGV:
                ////string _id1 = model.LSGV_GV_MA_CU;
                ////string _id2 = model.LSGV_DVGTVT_MA_CU;
                //var _dgv = _db.GetOne<DGV>(o => o.GV_MA == model.DCP_GV_MA && o.GV_DVGTVT_MA == model.DCP_GV_DVGTVT_MA);
                //_dgv.GV_ACTIVE = "1";
                //_db.Update<DGV>(_dgv);
                model.CB_PT_DVGTVT_MA_QL = _db.GetOne<SDONVIGTVT>(x => x.DVGTVT_MA == "40").DVGTVT_TEN;
                model.DATETIME_NOW = "Ngày " + DateTime.Now.Day.ToString() + " tháng " + DateTime.Now.Month.ToString() + " Năm " + DateTime.Now.Year.ToString();
                //model.DCP_GV_HODEM = hodem + " " + Ten;
                if (model.ExportWord == "Xuất giấy phép")
                {
                    byte[] contentFile = null;
                    contentFile = GPS.ENTITYS.EXPORTWORD_DPT_Export.EXPORT_DPT_Export(Server.MapPath("~/Templates/GPS_Word/GP_XeTapLai.docx"), model, "DocxGenericReport");
                    string nameOutput = "GiayChungNhan_" + model.CB_PT_BIENSO + "_" + DateTime.Now.ToShortDateString() + ".docx";
                    return File(contentFile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", nameOutput);
                }
                else
                {
                    return View("Index");
                }
                //var param2 = new OracleParameter("pDVGTVT_MA", OracleDbType.Varchar2, (model.DCP_DVGTVT_MA == null ? DBNull.Value : (object)model.DCP_DVGTVT_MA), ParameterDirection.Input);
                //var param3 = new OracleParameter("pRET", OracleDbType.RefCursor, ParameterDirection.Output);
                //var entities = _db.DbContext.Database.SqlQuery<CrudModelDCPDVGTVT>("BEGIN GPS_CAPPHEP.GPS_CAPPHEP_DTLX(:pDVGTVT_MA,:pRET); end;", param2, param3).ToList();
                //GPS.COMMON.Helpers.CopyObject<DCPDVGTVT>(model, ref _model);
            }
            else
            {
                return View("Index");
            }
        }

        #endregion

        public ActionResult getBienSo(string ma_DVGT)
        {
            if (ma_DVGT != null)
            {
                ma_DVGT = ma_DVGT.Split(':')[0];
            }
            var districts = _db.Filter<DPT>(d => d.PT_DVGTVT_MA == ma_DVGT).Select(a => "<option value='" + a.PT_BIENSO + "'>" + a.PT_BIENSO + "</option>");
            return Content(string.Join("", districts));
        }
    }
}